package com.sencorsta.ids.talk.OpenHandler;

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.talk.proto.ImtalkAddressListByProto;
import com.sencorsta.ids.talk.proto.ImtalkFriendListByProto;
import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;

/**
* @description: 好友列表
* @author TAO
* @date 2019/6/20 11:46
*/

@ClientEvent("FriendList")
public class FriendListHandler extends OpenMessageHandler implements RedisService {

    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.debug("------------------------好友列表FriendList------------------------------");
        ImtalkFriendListByProto.FriendListRes.Builder res=ImtalkFriendListByProto.FriendListRes.newBuilder();
        try{
            ImtalkFriendListByProto.FriendListReq req=ImtalkFriendListByProto.FriendListReq.parseFrom(protobuf);
            res.setSign(req.getSign());//返回前端标识信息
            //获取好友列表
            Map<String, String> friendList= R_FRIEND.hgetAll(userId);


            for (String key: friendList.keySet()){
                JSONObject jsonObject2=JSONObject.parseObject(friendList.get(key));//得到当前的昵称
                jsonObject2.put("userId",key);
                jsonObject2.put("nickname",R_USER.hget(key,NICKNAME));
                jsonObject2.put("sex",R_USER.hget(key,SEX));
                jsonObject2.put("portrait",R_USER.hget(key,PORTRAIT));
                jsonObject2.put("signature",R_USER.hget(key,SIGNATURE));
                res.addFriendList(String.valueOf(jsonObject2));
            }


            Out.debug("好友列表"+friendList);
            Out.debug("好友列表res"+res.getFriendListList());

            //返回消息
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        }catch (InvalidProtocolBufferException e){
            e.printStackTrace();
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR)));
        }
    }
}
